package com.motorola.dp.jenkinsmonitor.service.util.xml;

import static com.motorola.dp.jenkinsmonitor.model.util.ResponseInputStream.closeQuietly;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;

import com.motorola.dp.jenkinsmonitor.model.util.HttpRequestParameters;
import com.motorola.dp.jenkinsmonitor.model.util.ResponseInputStream;
import com.motorola.dp.jenkinsmonitor.model.util.exception.ServiceException;
import com.motorola.dp.jenkinsmonitor.service.util.dom.DomConversionService;
import com.motorola.dp.jenkinsmonitor.service.util.http.HttpService;

@Service("remoteXmlParsingService")
public class DefaultRemoteXmlParsingService implements RemoteXmlParsingService {

    @Value("#{httpService}")
    private HttpService httpService;

    @Value("#{xmlParsingService}")
    private XmlParsingService xmlParsingService;

    @Value("#{domConversionService}")
    private DomConversionService domConversionService;

    public <T> T parseRemoteXml(HttpRequestParameters params, Class<T> entityClass) {
        ResponseInputStream remoteXmlStream = null;
        try {
            remoteXmlStream = httpService.fetchStream(params);
            Document parsedXml = xmlParsingService.parse(remoteXmlStream);
            T entity = domConversionService.convert(parsedXml, entityClass);

            return entity;
        } catch (Exception e) {
            throw new ServiceException("Could not fetch or convert entity", e);
        } finally {
            closeQuietly(remoteXmlStream);
        }
    }

    public void setHttpService(HttpService httpService) {
        this.httpService = httpService;
    }

    public void setXmlParser(XmlParsingService xmlParser) {
        this.xmlParsingService = xmlParser;
    }

    public void setDomConverter(DomConversionService domConverter) {
        this.domConversionService = domConverter;
    }

}
